<template>
  <div>
    <a-modal :title="title" :width="800" v-model:visible="visible" @ok="onSubmit">
      <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 7 }">
        <a-row>
          <a-col v-for="(i, idx) in appform" :key="idx + 'b'" :span="16">
            <a-form-item :label="i.label" :name="i.name">
              <a-input v-if="i.type === 'input' && i.name !== 'secret'" v-model:value="i.value" @change="valueChange" />
              <a-radio-group v-if="i.type === 'radio'" v-model:value="i.value" button-style="solid">
                <a-radio-button v-for="(e, num) in i.options" :value="e.value">{{ e.label }}</a-radio-button>
              </a-radio-group>
              <a-select v-if="i.type === 'select'" v-model:value="i.value" :mode="i.mode || ''" @change="valueChange" :options="i.options"></a-select>
              <a-textarea v-if="i.type === 'textarea'" v-model:value="i.value" :auto-size="{ minRows: 2, maxRows: 5 }" @change="valueChange" />
              <a-switch v-if="i.type === 'switch'" v-model:checked="i.value" :checkedValue="1" :unCheckedValue="0">
                <template #checkedChildren><check-outlined /></template>
                <template #unCheckedChildren><close-outlined /></template>
              </a-switch>
              <UploadImg v-if="i.type === 'img'" v-model:value="i.value"></UploadImg>
              <UploadFile v-if="i.type === 'upFile'" v-model:value="i.value" />
              <a-input-search
                @change="valueChange"
                v-if="i.type === 'inputtable'"
                v-model:value="i.value"
                enter-button="选择"
                @search="openAppTable"
              />
              <a-tree-select
                v-if="i.type === 'treeSelects'"
                v-model:value="i.value"
                style="width: 100%"
                :tree-data="treeData"
                :dropdown-style="{ maxHeight: '600px', overflow: 'auto' }"
                tree-checkable
                allow-clear
                tree-default-expand-all
                :show-checked-strategy="SHOW_PARENT"
                tree-node-filter-prop="title"
                :fieldNames="{ title: 'title', key: 'key', value: 'key' }"
                @change="valueChange"
              />
              <!-- <a-tree v-if="i.type === 'treeSelects'" checkable :tree-data="treeData" v-model:checkedKeys="checkedKeys"> </a-tree> -->
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <AppTable ref="appTableRef" v-model:value="selectedRowKeyList" @change="appTableChange"></AppTable>
  </div>
</template>
<script setup>
import { ref, nextTick, reactive, toRaw, onMounted, watch } from 'vue';
import { message, TreeSelect } from 'ant-design-vue';
import _ from 'lodash';
import UploadImg from '/@/components/file/img.vue';
import UploadFile from '/@/components/file/uploadFile.vue';
import { smartSentry } from '/@/lib/smart-sentry';
import { applicationManagementApi } from '/@/api/system/applicationManagement-api';
import { configureApi } from '/@/api/system/configure-api.js';
import AppTable from './app-table.vue';

const checkedKeys = ref([]);
// 基本信息form
const appform = ref([
  { label: '编码', name: 'id', value: '', type: 'input', options: [], disabled: false },
  { label: '策略名称', name: 'name', value: '', type: 'input', options: [], disabled: false },
  { label: '应用名称', name: 'appName', value: '', type: 'inputtable', options: [], disabled: false },
  {
    label: '账号映射',
    name: 'mapping',
    value: '',
    type: 'select',
    options: [
      { label: 'username', value: 'username' },
      { label: 'employeeNumber', value: 'employeeNumber' },
      { label: 'windowsAccount', value: 'windowsAccount' },
      { label: 'email', value: 'email' },
      { label: 'mobile', value: 'mobile' },
      { label: 'idCardNo', value: 'idCardNo' },
    ],
    disabled: false,
  },
  { label: '后缀', name: 'suffixes', value: '', type: 'input', options: [], disabled: false },
  { label: '部门列表', name: 'orgIdsList', value: '', type: 'treeSelects', options: [], disabled: false },
  // { label: '属性过滤器', name: 'filters', value: '', type: 'textarea', options: [], disabled: false },
  {
    label: '创建方式',
    name: 'createType',
    value: '',
    defaultValue: 'manual',
    type: 'radio',
    options: [
      { value: 'manual', label: '人工' },
      { value: 'automatic', label: '自动' },
    ],
    disabled: false,
  },
  { label: '状态', name: 'status', value: '', type: 'switch', options: [], disabled: false },
]);

const activeKey = ref(0);
// emit
const emit = defineEmits(['reload']);

// 组件ref
const formRef = ref();

const formDefault = {
  id: undefined,
};
let form = reactive({ ...formDefault });
const rules = {
  // name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  // protocol: [{ required: true, message: '请选择协议', trigger: 'change' }],
  // adapter: [{ required: true, message: '请输入', trigger: 'blur' }],
};
// 是否展示抽屉
const visible = ref(false);
const formType = ref(null);
const title = ref('');

function showDrawer(rowData, index, type) {
  title.value = type;
  formType.value = index;
  if (index) {
    //添加
    onClose();
  } else {
    //编辑
    appform.value.forEach((i) => {
      i.value = rowData[i.name] || '';
      form[i.name] = i.value;
      if (i.name == 'orgIdsList') {
        if (i.value) {
          i.value = i.value
            .split(',')
            .map((item) => item.trim())
            .filter((item) => item !== '');
        }
      }
    });
    Object.assign(form, rowData);
  }
 
  visible.value = true;
}

// 选择表格行
const selectedRowKeyList = ref([]);
function onSelectChange(selectedRowKeys) {
  selectedRowKeyList.value = selectedRowKeys;
}

function appTableChange(records) {
  form.appName = selectedRowKeyList.value[0];
  form.appId = records[0].id;
  appform.value.forEach((i) => {
    if (i.name == 'appName') {
      i.value = selectedRowKeyList.value[0];
      paramObj['appId'] = records[0].id;
    }
  });
  Object.assign(form);
}
const treeData = ref([]);
// 获取树形数据
function getTree() {
  configureApi.getOrgsTree().then((res) => {
    if (res.data.nodes.length) {
      treeData.value = buildTree(res.data.nodes);
    }
  });
}
const SHOW_PARENT = TreeSelect.SHOW_PARENT;

function buildTree(data) {
  const tree = [];
  const map = {};
  // 先把所有节点放入一个映射表
  data.forEach((item) => {
    map[item.key] = { title: item.title, key: item.key, parentKey: item.parentKey, children: [] };
  });

  // 构建树
  data.forEach((item) => {
    const { parentKey } = item;
    if (parentKey === '0') {
      // 如果是根节点
      tree.push(map[item.key]);
    } else {
      // 如果有父节点，则将当前节点添加到父节点的 children 中
      if (map[parentKey]) {
        map[parentKey].children.push(map[item.key]);
      }
    }
  });
  return tree;
}

// 获取分类下拉
const FindList = ref([]);
async function getFindList() {
  try {
    let res = await configureApi.queryFindList();
    FindList.value = res.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
    FindList.value.unshift({ label: 'ALL', value: '' });
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
  }
}
const appTableRef = ref(null);
// 选择列表
function openAppTable() {
  appTableRef.value.showModal();
}

//添加之前清空
function onClose() {
  appform.value.forEach((i) => {
    i.value = i.defaultValue || '';
    if (i.name == 'status') {
      i.value = 1;
    } else if (i.name == 'mapping') {
      i.value = 'username';
    } else if (i.name == 'orgIdsList') {
      i.value = [];
    }
  });
  visible.value = false;
}

const paramObj = {};

function valueChange() {
  Object.assign(paramObj);

  paramObj['switch_status'] = true;

  appform.value.forEach((i) => {
    console.log(i);
    if (i.name === 'select_authorizedGrantTypes' && i.value && i.value.length) {
      paramObj['authorizedGrantTypes'] = i.value.join(',');
    } else if (i.name === 'select_scope' && i.value && i.value.length) {
      paramObj['scope'] = i.value.join(',');
    } else if (i.name == 'orgIdsList') {
      paramObj[i.name] =
        Object.values(i.value)
          .map(Number) // 将每个值转换为数字
          .join(', ') + ',';
      // paramObj[i.name] = Object.values(i.value).join(', ');
    } else {
      paramObj[i.name] = i.value;
    }
  });
  Object.assign(form, paramObj);
}

async function onSubmit() {
  valueChange();

  formRef.value
    .validate()
    .then(async () => {
      // SmartLoading.show();
      try {
        let res;
        console.log(paramObj);
        //1 新增  0编辑
        if (formType.value == 1) {
          res = await configureApi.addAccountsstrategy(paramObj);
        } else {
          res = await configureApi.updateAccountsstrategy(paramObj);
        }

        message.success(`${form.id ? '修改' : '添加'}成功`);
        onClose();
        emit('reload');
      } catch (error) {
        smartSentry.captureError(error);
      } finally {
        // SmartLoading.hide();
      }
    })
    .catch((error) => {
      console.log('error', error);
      message.error('参数验证错误，请仔细填写表单数据!');
    });
}
onMounted(() => {
  getTree();
});
defineExpose({
  showDrawer,
});
</script>
